﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JULONG.WEB.Library
{
    public static partial class staticClass
    {
        public static List<T> ToEntityList<T>(this System.Data.DataTable obj) where T : new()
        {
            var re = new List<T>();
            foreach (System.Data.DataRow item in obj.Rows)
            {
                re.Add(item.ToEntity<T>());
            }

            return re;
        }

        public static T ToEntity<T>(this System.Data.DataRow obj) where T:new()
        {
            //取得列名
            var columns = obj.Table.Columns;
            var re = new T();

            foreach (System.Data.DataColumn item in columns)
            {
                re.SetValue(item.ColumnName, obj[item.ColumnName]);
            }
            return re;
        }

        /// <summary>
        /// 反射设置值
        /// </summary>
        /// <param name="target"></param>
        /// <param name="propName"></param>
        /// <param name="value"></param>
        public static void SetValue(this object target, string propName, object value)
        {
            Type type = target.GetType();

            try
            {
                type.GetProperty(propName).SetValue(target, value, null);
            }
            catch
            {
            }
        }


        /// <summary>
        /// 反射得到一个obj的成员
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <param name="propName"></param>
        /// <returns></returns>
        public static T GetValue<T>(this object target, string propName)
        {
            var p = GetValue(target, propName);
            if (p == null) return default(T);
            return (T)p;
        }

        /// <summary>
        /// 反射得到一个obj的成员
        /// </summary>
        /// <param name="target"></param>
        /// <param name="propName"></param>
        /// <returns></returns>
        public static object GetValue(this object target, string propName)
        {
            Type type = target.GetType();
            System.Reflection.PropertyInfo p = type.GetProperty(propName);
            if (p == null) return null;
            return p.GetValue(target, null);
        }

        /// <summary>
        /// 反射调用一个obj的方法
        /// </summary>
        /// <param name="target"></param>
        /// <param name="methodName"></param>
        public static void ExecMethod(this object target, string methodName)
        {
            Type type = target.GetType();
            System.Reflection.MethodInfo p = type.GetMethod(methodName);
            if (p == null) return;
            p.Invoke(target, null); //调用方法，无参数  
        }


    }
}
